/**
 * @file filename.cpp
 * @brief nullptr关键字用于标识空指针，与NULL不同，NULL为0
 * @author Monomania (1301519350@qq.com)
 * @version 0.1
 * @date 2021-09-23
 */
#include<iostream>
#include <vector> 
#include <string>
#include <list>
#include <map>
#include <queue> 
#include <stack>
#include <algorithm> // std::minmax_element
#include <boost/algorithm/string.hpp>
#include <functional>
#include <iterator>
// #define NDEBUG
#include <assert.h>
using namespace std;

#define OK 1
#define ERROR 0
#define TRUE true
#define FALSE false
// 定义一个不可能的数
#define INF   -99999  
#define MAXSIZE 20 /* 存储空间初始分配量 */

typedef int Status; 
typedef int SElemType; /* SElemType类型根据实际情况而定，这里假设为int */

// 链表结点
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

void visit_list(ListNode* head){
    ListNode* tmp = head;
    while(tmp != nullptr){
        cout << tmp->val << ' ';
        tmp = tmp->next;
    }
    cout << endl;
}


class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (!head){
            return head;
        }
        ListNode *fast = head;
        ListNode *slow = head;
        int cnt=0;
        for (int i = 0; i < n;i++){
            if (fast->next){
                fast = fast->next;
                cnt++;
            }
        }
        if ((n-cnt)==1){
            // 解决n等于链表元素个数的问题
            // cout << "in" <<endl;
            head=head->next;
            delete slow;
            return head;
        }
        while(fast->next){
            slow = slow->next;
            fast = fast->next;
        }
        ListNode *tmp = slow->next;
        slow->next = tmp->next;
        delete tmp;
        return head;
    }
};

int main(int argc, const char** argv) {
    Solution solu = Solution();
    ListNode *L1 = new ListNode(1);
    // L1->next = new ListNode(2);
    // L1->next->next = new ListNode(3);
    // L1->next->next->next = new ListNode(4);
    // L1->next->next->next->next = new ListNode(5);
    visit_list(L1);

    ListNode *L2 = solu.removeNthFromEnd(L1, 1);

    visit_list(L2);

    return 0;
}